import React from 'react';
import { Navigate, useLocation } from 'react-router-dom';
import { useUserStore } from '@/stores';

interface ProtectedRouteProps {
  children: React.ReactNode;
  requiresAuth?: boolean;
  roles?: string[];
  redirectTo?: string;
}

export const ProtectedRoute: React.FC<ProtectedRouteProps> = ({
  children,
  requiresAuth = false,
  roles = [],
  redirectTo = '/login'
}) => {
  const { isAuthenticated, user } = useUserStore();
  const location = useLocation();

  // 如果需要认证但用户未登录
  if (requiresAuth && !isAuthenticated) {
    return <Navigate to={redirectTo} state={{ from: location }} replace />;
  }

  // 如果需要特定角色但用户没有权限
  if (roles.length > 0 && (!user || !roles.some(role => user.roles?.includes(role)))) {
    return <Navigate to="/unauthorized" replace />;
  }

  return <>{children}</>;
};